package com.exam.demo.controller.login;


import com.exam.demo.domain.User;
import com.exam.demo.mapper.UserMapper;
import com.exam.demo.result.R;
import com.exam.demo.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserMapper baseMapper;


    @PostMapping()
    public Object login (User user){
         Map<String,Object> map = new HashMap<>();

         User res = baseMapper.getUserByNameAndPasswd(user);


         if(res != null){
             map.put("result","yes");
             map.put("token", TokenUtils.generateToken(res.getId().toString()));
         }

         return map;
    }

    @PostMapping("/register")
    public R<String> register (User user){
        Map<String,Object> map = new HashMap<>();
        if(!baseMapper.getUserByName(user).isEmpty()) return R.fail("该用户名已存在");


        int num = baseMapper.insert(user);
        return R.judge(num>0);
    }


}
